﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Helper;
using System.Net;
using System.IO;
using Newtonsoft.Json;
using Inpinke.Model.CustomClass;
using Inpinke.Helper;
using Inpinke.Model;
using Inpinke.BLL;
using Inpinke.Model.Enum;
using Inpinke.BLL.Session;

namespace inpinke.com.Controllers
{
    public class OAuthController : Controller
    {
        //
        // GET: /OAuth/

        public ActionResult Index()
        {
            return View();
        }

        public void SetLoginData(Inpinke_User loginUser)
        {
            //添加session  
            UserSession.CurrentUser = loginUser;

            //设置友言单点登录cookie 
            string loginStr = ConfigHelper.ReadConfig("UyanApi", "configuration/DESApiUrl");
            loginStr = string.Format(loginStr, loginUser.ID, loginUser.NickName, loginUser.Email, "", "");
            string CookieMi = UYanBLL.GetMi(loginStr);
            string cookieName = ConfigHelper.ReadConfig("UyanApi", "configuration/CookieName");
            HttpCookie cookie = new HttpCookie(cookieName);
            cookie.Value = CookieMi;
            //HttpContext.Current.Response.Cookies.Add(cookie);
            HttpContext.Response.Cookies.Add(cookie);
        }

        /// <summary>
        /// 豆瓣第三方登录回调
        /// </summary>
        /// <returns></returns>
        public ActionResult Douban(string code,string error)
        {
            if (!string.IsNullOrEmpty(error))
            {
                return RedirectToAction("index", "home");
            }
            if (string.IsNullOrEmpty(code))
            {
                string codeUrl = ConfigHelper.ReadConfig("OAuth", "configuration/doubanauthurl");
                return Redirect(codeUrl);
            }
            else
            {
                string codeUrl = ConfigHelper.ReadConfig("OAuth", "configuration/doubantokenurl");
                codeUrl = string.Format(codeUrl, code);
                string rStr = RequestHelper.CallWebPage(codeUrl.Split('?')[0], codeUrl.Split('?')[1], null);
                DoubanToken dtObj = JsonConvert.DeserializeObject<DoubanToken>(rStr);
                if (dtObj != null)
                {
                    string userUrl = ConfigHelper.ReadConfig("OAuth", "configuration/doubanuserurl");
                    rStr = RequestHelper.CallWebPage(string.Format(userUrl, dtObj.douban_user_id), "", null);
                    DoubanUser dbUser = JsonConvert.DeserializeObject<DoubanUser>(rStr);
                    if (dbUser != null)
                    {
                        Inpinke_User user = DBUserBLL.GetUserByOAuthID(dbUser.id, (int)LoginType.douban);
                        if (user == null)
                        {
                            user = new Inpinke_User()
                           {
                               UserAvatar = dbUser.large_avatar,
                               NickName = dbUser.name,
                               Email = "",
                               Password = ""
                           };
                            BaseResponse br = DBUserBLL.CreateUser(user);
                            if (!br.IsSuccess)
                            {
                                ViewBag.msg = br.Message;
                                return View("error");
                            }
                            Inpinke_User_OAuthLogin oaModel = new Inpinke_User_OAuthLogin()
                            {
                                OpenID = dbUser.id,
                                AccessToken = dtObj.access_token,
                                UserID = user.ID,
                                RefreshToken = dtObj.refresh_token,
                                LoginType = (int)LoginType.douban
                            };
                            br = DBUserBLL.AddOAuthLogin(oaModel);
                            if (!br.IsSuccess)
                            {
                                ViewBag.msg = br.Message;
                                return View("error");
                            }
                        }
                        if (user != null)
                        { 
                            SetLoginData(user);
                            string f = "";
                            if (string.IsNullOrEmpty(f) && Request.UrlReferrer != null)
                            {
                                f = Request.UrlReferrer.AbsolutePath;
                            }
                            if (Url.IsLocalUrl(f) && f.Length > 1 && f.StartsWith("/")
                      && !f.StartsWith("//") && !f.StartsWith("/\\"))
                            {
                                return Redirect(f);
                            }
                            else
                            {
                                return RedirectToAction("book", "my");
                            }
                        }
                    }
                }
            }
            ViewBag.msg = "豆瓣认证登录失败，请选择其他方式登录。";
            return View("error");
        }

        /// <summary>
        /// QQ第3方登录回调
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public ActionResult QQ(string code)
        {
            if (string.IsNullOrEmpty(code))
            {
                string codeUrl = ConfigHelper.ReadConfig("OAuth", "configuration/qqauthurl");
                return Redirect(codeUrl);
            }
            else
            {
                MD5Encrypt md5 = new MD5Encrypt();
                Session["QQLoginState"] = md5.GetMD5FromString(((new Random()).Next(1000000, 999999999)).ToString());
                string codeUrl = ConfigHelper.ReadConfig("OAuth", "configuration/qqtokenurl");
                codeUrl = string.Format(codeUrl, code,Session["QQLoginState"]);
                string rStr = RequestHelper.CallWebPage(codeUrl,"", null);
                //access_token=E2BB2F1EB6765349090FCF3192FA301D&expires_in=7776000&refresh_token=3869548827600ECFC8EEB8C5DCB0AB7B
                string[] rStrInfo = rStr.Split('&');
                string access_token = rStrInfo[0].Replace("access_token=", "");
                string expires_in = rStrInfo[1].Replace("expires_in=", "");
                string refresh_token = rStrInfo[2].Replace("refresh_token=", "");

                //callback( {"client_id":"100470942","openid":"66080A39EBFA74B6CD2717F1078B1C71"} );
                string userUrl = ConfigHelper.ReadConfig("OAuth", "configuration/qquserurl");
                userUrl = string.Format(userUrl, access_token);
                rStr = RequestHelper.CallWebPage(userUrl, "", null);
                if (rStr.IndexOf("callback") == 0)
                {
                    rStr = rStr.Replace("callback(", "").Replace(")", "").Replace(";","").Trim();
                    QQOpenID qqOpenID = JsonConvert.DeserializeObject<QQOpenID>(rStr);
                    userUrl = ConfigHelper.ReadConfig("OAuth", "configuration/qquserinfourl");
                    userUrl = string.Format(userUrl, access_token, qqOpenID.openid);
                    rStr = RequestHelper.CallWebPage(userUrl, "", null);
                    QQUser qquser = JsonConvert.DeserializeObject<QQUser>(rStr);
                    if (qquser!=null&&qquser.ret == 0)
                    {
                        Inpinke_User user = DBUserBLL.GetUserByOAuthID(qqOpenID.openid, (int)LoginType.qq);
                    
                        if (user == null)
                        {
                            user = new Inpinke_User()
                            {
                                UserAvatar = qquser.figureurl_qq_2,
                                NickName = qquser.nickname,
                                Email = "",
                                Password = ""
                            };
                            BaseResponse br = DBUserBLL.CreateUser(user);
                            if (!br.IsSuccess)
                            {
                                ViewBag.msg = br.Message;
                                return View("error");
                            }
                            Inpinke_User_OAuthLogin oaModel = new Inpinke_User_OAuthLogin()
                            {
                                OpenID = qqOpenID.openid,
                                AccessToken = access_token,
                                UserID = user.ID,
                                RefreshToken = refresh_token,
                                LoginType = (int)LoginType.qq
                            };
                            br = DBUserBLL.AddOAuthLogin(oaModel);
                            if (!br.IsSuccess)
                            {
                                ViewBag.msg = br.Message;
                                return View("error");
                            }
                        }
                        if (user != null)
                        {
                            SetLoginData(user);
                            string f = "";
                            if (string.IsNullOrEmpty(f) && Request.UrlReferrer != null)
                            {
                                f = Request.UrlReferrer.AbsolutePath;
                            }
                            if (Url.IsLocalUrl(f) && f.Length > 1 && f.StartsWith("/")
                      && !f.StartsWith("//") && !f.StartsWith("/\\"))
                            {
                                return Redirect(f);
                            }
                            else
                            {
                                return RedirectToAction("book", "my");
                            }
                        }
                    }
                }
            }
            ViewBag.msg = "QQ认证登录失败，请选择其他方式登录。";
            return View("error");
        }

        /// <summary>
        /// 微博第3方登录回调
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public ActionResult Weibo(string code)
        {
            if (string.IsNullOrEmpty(code))
            {
                string codeUrl = ConfigHelper.ReadConfig("OAuth", "configuration/weiboauthurl");
                return Redirect(codeUrl);
            }
            else
            { 
                string codeUrl = ConfigHelper.ReadConfig("OAuth", "configuration/weibotokenurl");
                codeUrl = string.Format(codeUrl, code);
                string rStr = RequestHelper.CallWebPage(codeUrl.Split('?')[0], codeUrl.Split('?')[1], null);
                WeiboToken wToken = JsonConvert.DeserializeObject<WeiboToken>(rStr);

                string userUrl = ConfigHelper.ReadConfig("OAuth", "configuration/weibouserurl");
                userUrl = string.Format(userUrl, wToken.access_token);
                rStr = RequestHelper.CallWebPage(userUrl.Split('?')[0], userUrl.Split('?')[1], null);
                if (rStr.IndexOf("{") == 0)
                {
                    WeiboOpenID wOpenID = JsonConvert.DeserializeObject<WeiboOpenID>(rStr);
                    userUrl = ConfigHelper.ReadConfig("OAuth", "configuration/weibouserinfourl");
                    userUrl = string.Format(userUrl, wToken.access_token, wOpenID.uid);
                    rStr = RequestHelper.CallWebPage(userUrl, "", null);
                    WeiboUser qquser = JsonConvert.DeserializeObject<WeiboUser>(rStr);
                    if (qquser != null)
                    {
                        Inpinke_User user = DBUserBLL.GetUserByOAuthID(wOpenID.uid, (int)LoginType.weibo);

                        if (user == null)
                        {
                            user = new Inpinke_User()
                            {
                                UserAvatar = qquser.avatar_large,
                                NickName = qquser.screen_name,
                                Email = "",
                                Password = ""
                            };
                            BaseResponse br = DBUserBLL.CreateUser(user);
                            if (!br.IsSuccess)
                            {
                                ViewBag.msg = br.Message;
                                return View("error");
                            }
                            Inpinke_User_OAuthLogin oaModel = new Inpinke_User_OAuthLogin()
                            {
                                OpenID = wOpenID.uid,
                                AccessToken = wToken.access_token,
                                UserID = user.ID,
                                RefreshToken = "",
                                LoginType = (int)LoginType.weibo
                            };
                            br = DBUserBLL.AddOAuthLogin(oaModel);
                            if (!br.IsSuccess)
                            {
                                ViewBag.msg = br.Message;
                                return View("error");
                            }
                        }
                        if (user != null)
                        {
                            SetLoginData(user);
                            string f = "";
                            if (string.IsNullOrEmpty(f) && Request.UrlReferrer != null)
                            {
                                f = Request.UrlReferrer.AbsolutePath;
                            }
                            if (Url.IsLocalUrl(f) && f.Length > 1 && f.StartsWith("/")
                      && !f.StartsWith("//") && !f.StartsWith("/\\"))
                            {
                                return Redirect(f);
                            }
                            else
                            {
                                return RedirectToAction("book", "my");
                            }
                        }
                    }
                }
            }
            ViewBag.msg = "QQ认证登录失败，请选择其他方式登录。";
            return View("error");
        }
    }
}
